package com.joysuch.wwyt.list.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.list.bean.*;
import com.joysuch.wwyt.list.entity.BpListType;
import com.joysuch.wwyt.list.mapper.BpListTypeMapper;
import com.joysuch.wwyt.list.service.BpListBizService;
import com.joysuch.wwyt.list.service.BpListTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 清单类型Service
 * </p>
 *
 * @author xiaoying
 * @since 2021-05-17
 */
@Service
public class BpListTypeServiceImpl extends ServiceImpl<BpListTypeMapper, BpListType> implements BpListTypeService {

    @Autowired
    private BpListTypeMapper bpListTypeMapper;

    @Autowired
    private BpListBizService bpListBizService;

    @Override
    public List<BpListTypeTreeBean> listTree() {
        List<BpListTypeTreeBean> list = new ArrayList<>();
        List<BpListType> all = list(this.getTypeQueryWrapper());
        if (all != null && !all.isEmpty()) {
            Map<Long, BpListTypeTreeBean> treeMap = new HashMap<>();
            for (BpListType type : all) {
                BpListTypeTreeBean bean = new BpListTypeTreeBean();
                bean.setId(type.getId());
                bean.setLabel(type.getName());
                bean.setShowOrder(type.getShowOrder());
                bean.setChildren(new ArrayList<>());
                treeMap.put(type.getId(), bean);
                if (type.getParentId() == null || type.getParentId() == 0) {
                    list.add(bean);
                } else {
                    BpListTypeTreeBean parent = treeMap.get(type.getParentId());
                    parent.getChildren().add(bean);
                    Collections.sort(parent.getChildren());
                    treeMap.put(parent.getId(), parent);
                }
            }
        }
        Collections.sort(list);
        return list;
    }

    @Override
    public ResultBean save(BpListTypeEditBean bean) {
        BpListType bizType = null;
        // 是否新增
        boolean isNew = false;

        if (bean.getId() == null || bean.getId() == 0) {
            isNew = true;
            bizType = new BpListType();
        } else {
            bizType = bpListTypeMapper.selectById(bean.getId());
        }
        BeanUtils.copyProperties(bean, bizType);
        // 类型唯一校验
        if (checkDuplicateName(bean, isNew)) {
            return ResultBean.wrapErrorResultDefault("类型名称已经存在，不能重复");
        }
        if (isNew) {
            bpListTypeMapper.insert(bizType);
        } else {
            bpListTypeMapper.updateById(bizType);
        }


        return ResultBean.success(bizType);
    }

    @Override
    public ResultBean deleteById(Long id) {
        BpListBizQueryBean queryBean = new BpListBizQueryBean();
        queryBean.setTypeId(id);
        queryBean.setPage(0);
        queryBean.setSize(10);
        Page<BpListBizListBean> page = new Page<>(queryBean.getPage(), queryBean.getSize());
        if (bpListBizService.pageAll(page, queryBean).getTotal() > 0) {
            return ResultBean.wrapErrorResultDefault("当前类型还有关联的文档，请先删除关联文档后再尝试删除。");
        }
        bpListTypeMapper.deleteById(id);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public BpListTypeDetailBean getById(Long id) {
        BpListTypeDetailBean bean = new BpListTypeDetailBean();
        BpListType type = bpListTypeMapper.selectById(id);
        BeanUtils.copyProperties(type, bean);
        if (type.getParentId() != null) {
            BpListType parent = bpListTypeMapper.selectById(type.getParentId());
            if (parent != null) {
                bean.setParentName(parent.getName());
            }
        }
        return bean;
    }

    @Override
    public List<SimpleSelectListBean> listType() {
        List<SimpleSelectListBean> list = new ArrayList();
        List<BpListType> all = list(this.getTypeQueryWrapper());
        if (!CollectionUtils.isEmpty(all)) {
            for (BpListType type : all) {
                SimpleSelectListBean bean = new SimpleSelectListBean();
                bean.setLabel(type.getName());
                bean.setValue(type.getId());
                list.add(bean);
            }
        }
        return list;
    }

    private LambdaQueryWrapper<BpListType> getTypeQueryWrapper() {
        LambdaQueryWrapper<BpListType> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BpListType::getDeleteFlag, "0");
        lqw.likeRight(BpListType::getOrgCode, Context.getCompanyCode());
        lqw.eq(BpListType::getTenentId, Context.getCurrentTenantId());
        lqw.orderByAsc(BpListType::getId);
        return lqw;
    }

    private boolean checkDuplicateName(BpListTypeEditBean bean, boolean isNew) {
        boolean result = false;
        LambdaQueryWrapper<BpListType> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BpListType::getName, bean.getName());
        lqw.eq(BpListType::getDeleteFlag, "0");
        lqw.eq(BpListType::getTenentId, Context.getCurrentTenantId());
        lqw.likeRight(BpListType::getOrgCode, Context.getCompanyCode());
        if (bean.getParentId() == null) {
            lqw.isNull(BpListType::getParentId);
        } else {
            lqw.eq(BpListType::getParentId, bean.getParentId());
        }
        List<BpListType> list = bpListTypeMapper.selectList(lqw);
        if (isNew) {
            if (list != null && list.size() > 0) {
                return true;
            }
        } else {
            if (list == null || list.size() == 0) {
                return false;
            } else if (list.size() > 1) {
                return true;
            } else {
                return (list.get(0).getId() != bean.getId());
            }
        }
        return result;
    }


}
